﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Keepo.Models.Services;
using AlbumDesigner.Helpers;
using Keepo.Models;
using System.Web.Script.Serialization;

namespace AlbumDesigner.Controllers
{
    public class AlbumPagesController : Controller
    {
        //
        // GET: /AlbumPages/

        public ActionResult Index()
        {
            return View();
        }


        // Flex
        [HttpPost]
        public ActionResult GetAlbumPageById(int albumPageId = -1)
        {
            var export = AlbumsLogic.GetAlbumPageById(albumPageId);

            if (export == null)
            {
                return new HttpUnauthorizedResult("no permissions");
            }
            else
            {
                return Json(export);
            }
        }

        // Flex
        [HttpPost]
        public ActionResult GetAlbumPagesBySectionId(int sectionId = -1)
        {
            var sections = AlbumsLogic.GetAlbumPagesBySectionId(sectionId);
            return Json(sections);
        }

        // Flex
        [HttpPost]
        public ActionResult GetAlbumPagesByAlbumId(int albumId = -1)
        {
            var sections = AlbumsLogic.GetAlbumPagesByAlbumId(albumId);
            return Json(sections);
        }

        // Flex
        [HttpPost]
        public ActionResult GetPremadePageById(int premadePageId)
        {
            var page = AlbumsLogic.getPremadePageById(premadePageId);
            return Json(page);
        }

        // Flex
        [HttpPost]
        public ActionResult MoveAlbumPageByIdx(int sectionId, int srcPageIdx, int dstPageIdx)
        {
            return Json(AlbumsLogic.MoveAlbumPageByIdx(sectionId, srcPageIdx, dstPageIdx));
        }

        // Flex
        [HttpPost]
        public ActionResult GetNotesForPage(int pageId)
        {
            return Json(AlbumsLogic.getNotesForPage(pageId));
        }

        // Flex
        [HttpPost]
        public ActionResult SetNotesForPage(int pageId, string notes)
        {
            return Json(AlbumsLogic.setNotesForPage(pageId, notes));
        }

        // Flex
        [HttpPost]
        public ActionResult SavePage(int pageId, HttpPostedFileBase xmlFile, HttpPostedFileBase pageThumbnail, string imageIdsStr)
        {
            if (!AlbumsLogic.canUserEdit(AlbumPageId: pageId))
            {
                return new HttpUnauthorizedResult();
            }

            try
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();

                using (var db = new AlbumContext())
                {
                    var page = db.AlbumPages.Find(pageId);

                    AlbumHelper.CreateAlbumDirectories(page.AlbumSection.AlbumId);

                    if (page != null)
                    {
                        var xmlFileName = Server.MapPath("~/") + AlbumHelper.PageXmlUrl(page.AlbumSection.AlbumId, pageId);

                        // Save last backup separately 
                        if (System.IO.File.Exists(xmlFileName))
                        {
                            System.IO.File.Copy(xmlFileName, xmlFileName + ".bak", true);
                        }

                        // And zip all backups
                        PagesHelper.SavePageBackup(pageId);

                        xmlFile.SaveAs(xmlFileName);
                        AlbumsLogic.SetHasXml(pageId, true);

                        var thumbnailFileName = Server.MapPath("~/") + AlbumHelper.PageThumbnailUrl(page.AlbumSection.AlbumId, pageId);
                        pageThumbnail.SaveAs(thumbnailFileName);
                        AlbumsLogic.HasThumbnail(pageId, true);

                        var imageIds = serializer.Deserialize<int[]>(imageIdsStr);
                        AlbumsLogic.setImagePagePairs(pageId, imageIds);

                        // Report no render for this page
                        AlbumsLogic.SetHasRender(pageId, false);
                    }

                }

                return Json(true);
            }
            catch (Exception e)
            {
                return new HttpUnauthorizedResult(e.Message);
            }


        }

        // Flex
        [HttpPost]
        public ActionResult SavePageRender(int pageId, HttpPostedFileBase pageRender)
        {
            if (!AlbumsLogic.canUserEdit(AlbumPageId: pageId))
            {
                return new HttpUnauthorizedResult();
            }

            using (var db = new AlbumContext())
            {
                var page = db.AlbumPages.Find(pageId);

                if (page != null)
                {
                    var renderFileName = Server.MapPath("~/") + AlbumHelper.PageFullImage(page.AlbumSection.AlbumId, pageId);
                    pageRender.SaveAs(renderFileName);

                    // Report has render for this page
                    AlbumsLogic.SetHasRender(pageId, true);
                }

            }

            return Json(true);
        }

        // Flex
        [HttpPost]
        public ActionResult SavePremade(int pageId, HttpPostedFileBase xmlFile, HttpPostedFileBase pageThumbnail)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            using (var db = new AlbumContext())
            {
                var page = db.PremadePages.Find(pageId);

                if (page != null)
                {
                    var xmlFileName = Server.MapPath("~/") + AlbumHelper.PremadePageXml(pageId);
                    xmlFile.SaveAs(xmlFileName);
                    AlbumsLogic.SetHasXml(pageId, true);

                    var thumbnailFileName = Server.MapPath("~/") + AlbumHelper.PremadePageThumbnailUrl(pageId);
                    pageThumbnail.SaveAs(thumbnailFileName);
                    AlbumsLogic.HasThumbnail(pageId, true);

                    // Report premade page was saved
                    AlbumsLogic.setPremadePageSaved(pageId);
                }

            }

            return Json(true);
        }

        // Flex
        [HttpPost]
        public ActionResult IsPageLocked(int pageId)
        {
            using (var db = new AlbumContext())
            {
                var page = db.AlbumPages.Find(pageId);

                if (page != null)
                {
                    return Json(new { LockLeftSide = page.LockLeftSide, LockRightSide = page.LockRightSide }, JsonRequestBehavior.AllowGet);
                }
            }

            return Json("Error, Page not found", JsonRequestBehavior.AllowGet);
        }

        // [HttpPost]
        public ActionResult SetPageLock(int pageId, string side, bool isLock)
        {
            using (var db = new AlbumContext())
            {
                var page = db.AlbumPages.Find(pageId);

                if (page != null)
                {
                    switch (side.ToLower())
                    {
                        case "left":
                            page.LockLeftSide = isLock;
                            break;

                        case "right":
                            page.LockRightSide = isLock;
                            break;

                        default:
                            return Json(false, JsonRequestBehavior.AllowGet);
                    }

                    db.SaveChanges();
                }
                else
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
            }

            return Json(true, JsonRequestBehavior.AllowGet);
        }


        // TEST
        public ActionResult SavePageBackup(int pageId)
        {
            try
            {
                PagesHelper.SavePageBackup(pageId);
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            
        }
    }


    
}
